import React, { useEffect } from 'react';
import { Modal, Form } from 'antd';
import type { FormInstance } from 'antd';
import type { FormMode } from '@/types';

export interface ModalFormItem {
  name: string;
  label: string;
  component: React.ReactNode;
  rules?: any[];
  hidden?: boolean;
  valuePropName?: string;
  initialValue?: any;
}

interface ModalFormProps {
  visible: boolean;
  title: string;
  mode: FormMode;
  items: ModalFormItem[];
  initialValues?: Record<string, any>;
  onSubmit: (values: any) => Promise<void>;
  onCancel: () => void;
  width?: number;
  form?: FormInstance;
}

const ModalForm: React.FC<ModalFormProps> = ({
  visible,
  title,
  mode,
  items,
  initialValues,
  onSubmit,
  onCancel,
  width = 600,
  form: externalForm,
}) => {
  const [internalForm] = Form.useForm();
  const form = externalForm || internalForm;
  const [loading, setLoading] = React.useState(false);

  useEffect(() => {
    if (visible) {
      if (initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
      }
    }
  }, [visible, initialValues, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      await onSubmit(values);
      form.resetFields();
      onCancel();
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  const isView = mode === 'view';

  return (
    <Modal
      title={title}
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      width={width}
      okText={mode === 'create' ? '创建' : '保存'}
      cancelText="取消"
      okButtonProps={{ disabled: isView }}
      styles={{
        body: {
          maxHeight: '65vh',
          overflowY: 'auto',
          paddingRight: '8px',
        }
      }}
    >
      <Form form={form} layout="vertical" disabled={isView}>
        {items.map((item) =>
          item.hidden ? null : (
            <Form.Item 
              key={item.name} 
              name={item.name} 
              label={item.label} 
              rules={item.rules}
              valuePropName={item.valuePropName}
              initialValue={item.initialValue}
            >
              {item.component}
            </Form.Item>
          ),
        )}
      </Form>
    </Modal>
  );
};

export default ModalForm;

